package com.example.gdtest;

import android.media.MediaPlayer;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.widget.TextView;
import android.widget.Toast;
import androidx.appcompat.app.AppCompatActivity;
import android.os.Bundle;
import com.amap.api.location.AMapLocation;
import com.amap.api.location.AMapLocationClient;
import com.amap.api.location.AMapLocationClientOption;
import com.amap.api.location.AMapLocationListener;
import com.amap.api.maps.AMap;
import com.amap.api.maps.CameraUpdateFactory;
import com.amap.api.maps.LocationSource;
import com.amap.api.maps.MapView;
import com.amap.api.maps.model.LatLng;
import com.amap.api.maps.model.Marker;
import com.amap.api.maps.model.MarkerOptions;
import org.eclipse.paho.client.mqttv3.*;
import org.eclipse.paho.client.mqttv3.persist.MemoryPersistence;

import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;

public class MainActivity extends AppCompatActivity implements LocationSource, AMapLocationListener {
    //请求权限码
    private static final int REQUEST_PERMISSIONS = 9527;

    MapView mMapView = null;
    TextView text_longitudeLatitude;

    //声明mlocationClient对象
    public AMapLocationClient mlocationClient;
    //声明mLocationOption对象
    public AMapLocationClientOption mLocationOption = null;

/*****************************MQTT*****************************/
    private static final String TAG = "System.out.println";
    private String host = "tcp://120.77.86.191:1883";
    private String userName = "root";
    private String passWord = "root";
    private String mqtt_id = "smarthomeAndroid";
    private String mqtt_pub_topic = "/mysmarthome/sub";
    private String mqtt_sub_topic = "/mysmarthome/pub";
    private int led_flag =1;
    private ScheduledExecutorService scheduler;

    private MqttClient client;
    private MqttConnectOptions options;
    private Handler handler;
/*****************************MQTT*****************************/

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        //获取地图控件引用
        mMapView = (MapView) findViewById(R.id.map);
        text_longitudeLatitude = findViewById(R.id.text_longitudeLatitude);

        /*****************************gdMap*****************************/
        //在activity执行onCreate时执行mMapView.onCreate(savedInstanceState)，创建地图
        mMapView.onCreate(savedInstanceState);
        //初始化地图控制器对象
        AMap aMap = null;
        if (aMap == null) {
            aMap = mMapView.getMap();
        }

        //位置更改监听
        OnLocationChangedListener mListener;

        // 设置定位监听
        aMap.setLocationSource(this);
        // 设置为true表示显示定位层并可触发定位，false表示隐藏定位层并不可触发定位，默认是false
        aMap.setMyLocationEnabled(true);
        /*****************************gdMap*****************************/

        /*****************************MQTT*****************************/
        Mqtt_init();
        startReconnect();
        this.handler = new Handler() {

            public void handleMessage(Message msg) {
                super.handleMessage(msg);
                int i = msg.what;
                char c = 3;
                char c2 = 1;
                char c3 = 0;
                if (i == 3) {
                    String s = msg.obj.toString();

                    Log.i("allTag",s);

                    String[] a = s.split(",");  //以 “，”分割 s
                    for (i=0;i<a.length;i++){          //输出分割后数组
                        Log.i("imSplit",a[i]);
                    }

                    String Longitude_str = a[0].substring(13);
                    String Latitude_str = a[1].substring(11);
                    Log.i("LoLa_str",Longitude_str+","+Latitude_str);

                    double Logitude_dou = Double.parseDouble(Longitude_str);
                    double Latitude_dou = Double.parseDouble(Latitude_str);
                    Log.i("LoLa_dou",Logitude_dou+","+Latitude_dou);



                    /*****************************gdMap*****************************/
                   /* double latitude = 40.012707;
                    double longitude = 116.385584;*/

                    StringBuffer stringBuffer = new StringBuffer();
                    stringBuffer.append("纬度：" + Latitude_dou + "\n");
                    stringBuffer.append("经度：" + Logitude_dou + "\n");

                    text_longitudeLatitude.setText(stringBuffer.toString());
                    Log.i("addTag",stringBuffer.toString());
                    moveMap(Latitude_dou,Logitude_dou);    //移动地图中心
                    addMarkerToMap(Latitude_dou,Logitude_dou);
                    /*****************************gdMap*****************************/
                } else if (i == 30) {
                    Toast.makeText(MainActivity.this, "连接失败", Toast.LENGTH_LONG).show();
                } else if (i == 31) {
                    Toast.makeText(MainActivity.this, "连接成功", Toast.LENGTH_LONG).show();
                    try {
                        MainActivity.this.client.subscribe(MainActivity.this.mqtt_sub_topic, 1);
                    } catch (MqttException e) {
                        e.printStackTrace();
                    }
                }
            }
        };
        /*****************************MQTT*****************************/

        
    }
    /*****************************MQTT*****************************/
    private void Mqtt_init()
    {
        try {
            //host为主机名，test为clientid即连接MQTT的客户端ID，一般以客户端唯一标识符表示，MemoryPersistence设置clientid的保存形式，默认为以内存保存
            client = new MqttClient(host, mqtt_id,
                    new MemoryPersistence());
            //MQTT的连接设置
            options = new MqttConnectOptions();
            //设置是否清空session,这里如果设置为false表示服务器会保留客户端的连接记录，这里设置为true表示每次连接到服务器都以新的身份连接
            options.setCleanSession(false);
            //设置连接的用户名
            options.setUserName(userName);
            //设置连接的密码
            options.setPassword(passWord.toCharArray());
            // 设置超时时间 单位为秒
            options.setConnectionTimeout(10);
            // 设置会话心跳时间 单位为秒 服务器会每隔1.5*20秒的时间向客户端发送个消息判断客户端是否在线，但这个方法并没有重连的机制
            options.setKeepAliveInterval(20);
            //设置回调
            client.setCallback(new MqttCallback() {
                @Override
                public void connectionLost(Throwable cause) {
                    //连接丢失后，一般在这里面进行重连
                    System.out.println("connectionLost----------");
                    startReconnect();
                }
                @Override
                public void deliveryComplete(IMqttDeliveryToken token) {
                    //publish后会执行到这里
                    System.out.println("deliveryComplete---------"
                            + token.isComplete());
                }
                @Override
                public void messageArrived(String topicName, MqttMessage message)
                        throws Exception {
                    //subscribe后得到的消息会执行到这里面
                    System.out.println("messageArrived----------");
                    Message msg = new Message();
                    //封装message包
                    msg.what = 3;   //收到消息标志位
                    msg.obj =  message.toString();
                    //发送messge到handler
                    handler.sendMessage(msg);    // hander 回传

                    //提示音
                    playMedia();
                }
            });
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
    private void Mqtt_connect() {
        new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    if(!(client.isConnected()) )  //如果还未连接
                    {
                        client.connect(options);
                        Message msg = new Message();
                        msg.what = 31;
                        // 没有用到obj字段
                        handler.sendMessage(msg);
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                    Message msg = new Message();
                    msg.what = 30;
                    // 没有用到obj字段
                    handler.sendMessage(msg);
                }
            }
        }).start();
    }
    private void startReconnect() {
        scheduler = Executors.newSingleThreadScheduledExecutor();
        scheduler.scheduleAtFixedRate(new Runnable() {
            @Override
            public void run() {
                if (!client.isConnected()) {
                    Mqtt_connect();
                }
            }
        }, 0 * 1000, 10 * 1000, TimeUnit.MILLISECONDS);
    }
    private void publishmessageplus(String topic,String message2)
    {
        if (client == null || !client.isConnected()) {
            return;
        }
        MqttMessage message = new MqttMessage();
        message.setPayload(message2.getBytes());
        try {
            client.publish(topic,message);
        } catch (MqttException e) {

            e.printStackTrace();
        }
    }
    /*****************************MQTT*****************************/
public void playMedia(){
    MediaPlayer mediaPlayer = null;
    mediaPlayer = new MediaPlayer();
    mediaPlayer = MediaPlayer.create(getApplicationContext(), R.raw.music2);

    mediaPlayer.start();
}
    /*****************************gdMap*****************************/
    //地图方法重写1-地图生命周期管理方法
    @Override
    protected void onDestroy() {
        super.onDestroy();
        //在activity执行onDestroy时执行mMapView.onDestroy()，销毁地图
        mMapView.onDestroy();
    }
    @Override
    protected void onResume() {
        super.onResume();
        //在activity执行onResume时执行mMapView.onResume ()，重新绘制加载地图
        mMapView.onResume();
    }
    @Override
    protected void onPause() {
        super.onPause();
        //在activity执行onPause时执行mMapView.onPause ()，暂停地图的绘制
        mMapView.onPause();
    }
    @Override
    protected void onSaveInstanceState(Bundle outState) {
        super.onSaveInstanceState(outState);
        //在activity执行onSaveInstanceState时执行mMapView.onSaveInstanceState (outState)，保存地图当前的状态
        mMapView.onSaveInstanceState(outState);
    }
    //地图方法重写1

    //地图方法重写2
    //以某个经纬度为中心来展示地图
    protected void moveMap(double latitude, double longtiude)
    {
        AMap aMap = mMapView.getMap();

        LatLng lagLng = new LatLng(latitude, longtiude);

        //移动amap地图 以之前的缩放比例展示
        aMap.animateCamera(CameraUpdateFactory.newLatLngZoom(lagLng, aMap.getCameraPosition().zoom));
    }

    //向固定的经纬度添加一个标记
    protected void addMarkerToMap(double latitude, double longitude)
    {
        AMap aMap = mMapView.getMap();
        LatLng latLng = new LatLng(latitude,longitude);
        final Marker marker = aMap.addMarker(new MarkerOptions().position(latLng).title("北京").snippet("DefaultMarker"));

    }
    //地图方法重写2


    @Override
    public void onLocationChanged(AMapLocation aMapLocation) {

    }

    @Override
    public void activate(OnLocationChangedListener onLocationChangedListener) {

    }

    @Override
    public void deactivate() {

    }

    @Override
    public void onPointerCaptureChanged(boolean hasCapture) {
        super.onPointerCaptureChanged(hasCapture);
    }

    /*****************************gdMap*****************************/


}